package cn.pupil.springframework.beans.factory;

import cn.pupil.springframework.beans.BeansException;
import cn.pupil.springframework.beans.PropertyValue;
import cn.pupil.springframework.beans.PropertyValues;
import cn.pupil.springframework.beans.factory.config.BeanDefinition;
import cn.pupil.springframework.beans.factory.config.BeanFactoryPostProcessor;
import cn.pupil.springframework.core.io.DefaultResourceLoader;
import cn.pupil.springframework.core.io.Resource;
import cn.pupil.springframework.util.StringValueResolver;

import java.io.IOException;
import java.util.Properties;

/**
 * @Description: 属性占位符配置器，在 Bean 对象实例化之前，改变属性信息，完成对配置文件的加载以及摘取占位符中的在属性文件里的配置
 * @Author: pupil
 * @Date: 2024/11/24 下午 3:57
 */
public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {

    /**
     * Default placeholder prefix: {@value}
     * 默认占位符前缀
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

    /**
     * Default placeholder suffix: {@value}
     * 默认占位符后缀
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    // 资源路径
    private String location;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 加载属性文件
        try {
            // 获取资源加载器
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            // 加载属性配置文件资源（.properties \ .yaml \ .yml的文件）
            Resource resource = resourceLoader.getResource(location);
            // 将资源转换成属性对象
            Properties properties = new Properties();
            properties.load(resource.getInputStream());

            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String beanName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                    Object value = propertyValue.getValue();
                    // 判读是否为字符串类型，不是跳过当前循环迭代
                    if (!(value instanceof String)) continue;
                    value = resolvePlaceholder((String) value, properties);
                    // 将提取到的配置新放置到属性配置中
                    propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(), value));
                }
            }

            // 向容器中添加字符串解析器，提供解析@Value注释使用
            StringValueResolver valueResolver  = new PlaceholderResolvingStringValueResolver(properties);
            beanFactory.addEmbeddedValueResolver(valueResolver);
        } catch (IOException e) {
            throw new BeansException("Could not load properties", e);
        }
    }

    /**
     * 解析占位符
     *
     * @param value
     * @param properties
     * @return
     */
    private String resolvePlaceholder(String value, Properties properties) {
        String strVal = value;
        StringBuilder buffer = new StringBuilder(strVal);
        int startIdx = strVal.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
        int stopIdx = strVal.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
        if (startIdx != -1 && stopIdx != -1 && startIdx < stopIdx) {
            // 提取占位符中的属性键
            String propKey = strVal.substring(startIdx + 2, stopIdx);
            // 从属性文件中获取属性键对应的值
            String propVal = properties.getProperty(propKey);
            // 将提取到的配置新放置到属性配置中
            buffer.replace(startIdx, stopIdx + 1, propVal);
        }
        return buffer.toString();
    }

    /**
     * 设置资源路径
     *
     * @param location
     */
    public void setLocation(String location) {
        this.location = location;
    }


    private class PlaceholderResolvingStringValueResolver implements StringValueResolver {

        private final Properties properties;

        public PlaceholderResolvingStringValueResolver(Properties properties) {
            this.properties = properties;
        }

        @Override
        public String resolveStringValue(String strVal) {
            return PropertyPlaceholderConfigurer.this.resolvePlaceholder(strVal,properties);
        }
    }
}
